package com.heima.reggie.filter;
import com.alibaba.fastjson.JSON;
import com.heima.reggie.bean.Employee;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter2 extends UsernamePasswordAuthenticationFilter {
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            //如果不是post请求，那么直接抛出异常，因为一般登录操作，都是走post请求。
            if (!request.getMethod().equals("POST")) {
                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
            } else {
                Employee e = JSON.parseObject(request.getInputStream() , Employee.class ) ;
                request.getSession().setAttribute("employee", e);
                System.out.println("LoginFilter02:: 页面传递上来的对象：" + e);
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(e.getUsername(), e.getPassword());
                this.setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.attemptAuthentication(request,response);
    }
}
